import lrz from "lrz";

const compress = async function(file) {
  let imgUrl = URL.createObjectURL(file, { quality: 0 });
  let quality = 1;
  // 根据图片大小设置压缩比例
  if (file.size >= 500 * 1024 && file.size < 1024 * 1024 * 5) {
    quality = 0.8;
  } else if (file.size > 100 * 1024 && file.size < 500 * 1024) {
    quality = 0.5;
  } else {
    quality = 0.8;
  }
  console.log("before Compress", file.size/1024);
  //  console.log('quality', quality)
  const imgSrc = window.URL.createObjectURL(file);
  let img = new Image();
  img.src = imgSrc;
  // 我在这里就可以获取到图片的宽度和高度了 img.width 、img.height
  //    console.log("width",img.width)
  const width = img.width > 1200 ? 1200 : img.width; // 设置图片宽度，避免图片过大模糊
  //    _this.upload(width, quality)
  const compressedImg = await lrz(imgUrl, { width: width, quality: quality }).then(
    (rst) => {
      // rst.fileLen为压缩后文件大小，rst.file为压缩后的图片文件
      let after = rst.fileLen / 1024;
    //   console.log("rst", rst);
      console.log("after Compress", quality, after);
      return rst;
      // 上传图片
    }
  );
  //  console.log("imgUrl", imgUrl);
//   console.log("rstout", compressedImg);
  return compressedImg;
};

export default compress;
